<template>
  <div class="map-module">
    <!-- 顶部工具栏 -->
    <div class="map-toolbar">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索地点、地址..."
          clearable
          @keyup.enter="handleSearch"
          @clear="clearSearchMarkers"
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch" type="primary">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 功能按钮组 -->
      <div class="function-buttons">
        <el-button-group>
          <el-button :type="currentTool === 'measure' ? 'primary' : ''" @click="activateTool('measure')">
            <el-icon><Connection /></el-icon>
            测距
        </el-button>
          <el-button @click="showRoutePanel = true">
            <el-icon><Guide /></el-icon>
            路线规划
        </el-button>
          <el-button @click="locateUser">
            <el-icon><Aim /></el-icon>
            定位
          </el-button>
        </el-button-group>
      </div>

      <!-- 地图类型切换 -->
      <div class="map-type-switch">
        <el-radio-group v-model="mapType" @change="changeMapType">
          <el-radio-button label="standard">标准地图</el-radio-button>
          <el-radio-button label="satellite">卫星地图</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <!-- 地图容器 -->
    <div class="map-main-container">
      <div class="map-container-wrapper">
        <div id="amap-container" class="amap-container"></div>
        
        <!-- 地图控制按钮 -->
        <div class="map-controls">
          <el-button circle @click="zoomIn">
            <el-icon><Plus /></el-icon>
        </el-button>
          <el-button circle @click="zoomOut">
            <el-icon><Minus /></el-icon>
        </el-button>
    </div>
    
        <!-- 测量结果显示 -->
        <div v-if="measureResult" class="measure-result">
          <el-alert :title="measureResult" type="success" closable @close="clearMeasure" />
      </div>
  </div>
    </div>

    <!-- 路线规划面板 -->
    <el-drawer 
      v-model="showRoutePanel" 
      title="🧭 路线规划" 
      size="450px" 
      direction="rtl"
      @close="handleRoutePanelClose"
    >
      <div class="route-panel">
        <el-form :model="routeForm" label-width="80px" label-position="top">
          <!-- 起点 -->
          <el-form-item>
            <template #label>
              <span>起点</span>
              <span style="color: #909399; font-size: 12px; margin-left: 6px;">（如果定位错误请重新点击）</span>
            </template>
            <el-input 
              v-model="routeForm.start" 
              placeholder="请输入起点地址"
              clearable
              size="large"
            >
              <template #prefix>
                <el-icon color="#67C23A"><Location /></el-icon>
</template>
            </el-input>
            <div class="location-actions">
              <el-button text type="primary" @click="useCurrentLocation" size="small">
                <el-icon><Aim /></el-icon>
                使用当前位置
              </el-button>
              <el-button text type="info" @click="selectFromMap('start')" size="small">
          <el-icon><MapLocation /></el-icon>
                地图选点
        </el-button>
            </div>
          </el-form-item>
          
          <!-- 交换按钮 -->
          <div class="swap-button-wrapper">
            <el-button circle @click="swapStartEnd" size="small">
              <el-icon><Sort /></el-icon>
            </el-button>
          </div>
          
          <!-- 终点 -->
          <el-form-item label="终点">
            <el-input 
              v-model="routeForm.end" 
              placeholder="请输入终点地址"
              clearable
              size="large"
            >
              <template #prefix>
                <el-icon color="#F56C6C"><Location /></el-icon>
              </template>
            </el-input>
            <div class="location-actions">
              <el-button text type="info" @click="selectFromMap('end')" size="small">
                <el-icon><MapLocation /></el-icon>
                地图选点
        </el-button>
      </div>
          </el-form-item>
          
          
          <!-- 操作按钮 -->
          <el-form-item>
            <el-space direction="vertical" style="width: 100%;" :size="10">
              <el-button 
                type="primary" 
                @click="planRoute" 
                size="large"
                :loading="routeLoading"
                style="width: 100%;"
              >
                <el-icon v-if="!routeLoading"><Guide /></el-icon>
                {{ routeLoading ? '规划中...' : '开始规划' }}
        </el-button>
              <el-button 
                @click="clearRoute" 
                size="large"
                style="width: 100%;"
              >
                <el-icon><Delete /></el-icon>
                清除路线
        </el-button>
            </el-space>
          </el-form-item>
        </el-form>

        <!-- 路线结果 -->
        <div v-if="routeResult" class="route-result">
          <el-divider content-position="left">
            <el-icon><TrendCharts /></el-icon>
            路线详情
          </el-divider>
          
          <el-card shadow="hover" class="route-info-card">
            <div class="route-info-item">
              <div class="info-label">
                <el-icon><Guide /></el-icon>
                <span>路线方案</span>
      </div>
              <div class="info-value">{{ routeResult.routeName }}</div>
    </div>
    
            <el-divider />
            
            <div class="route-info-item">
              <div class="info-label">
                <el-icon><Connection /></el-icon>
                <span>总距离</span>
      </div>
              <div class="info-value highlight">{{ routeResult.distance }}</div>
            </div>
            
            <el-divider />
            
            <div class="route-info-item">
              <div class="info-label">
                <el-icon><Timer /></el-icon>
                <span>预计时间</span>
              </div>
              <div class="info-value highlight">{{ routeResult.duration }}</div>
            </div>
            
            <el-divider v-if="routeResult.taxiFee" />
            
            <div v-if="routeResult.taxiFee" class="route-info-item">
              <div class="info-label">
                <el-icon><Money /></el-icon>
                <span>打车费用</span>
              </div>
              <div class="info-value">约 {{ routeResult.taxiFee }} 元</div>
            </div>
          </el-card>
          
          <!-- 路线步骤 -->
          <div v-if="routeSteps.length > 0" class="route-steps">
            <el-divider content-position="left">
              <el-icon><List /></el-icon>
              导航步骤
            </el-divider>
            <el-timeline>
              <el-timeline-item 
                v-for="(step, index) in routeSteps" 
                :key="index"
                :icon="index === 0 ? Location : (index === routeSteps.length - 1 ? Aim : Guide)"
                :color="index === 0 ? '#67C23A' : (index === routeSteps.length - 1 ? '#F56C6C' : '#409EFF')"
              >
                <div class="step-content">
                  <div class="step-instruction">{{ step.instruction }}</div>
                  <div class="step-info">
                    <el-tag size="small" type="info">{{ step.distance }}</el-tag>
                    <el-tag size="small" type="warning" v-if="step.duration">{{ step.duration }}</el-tag>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Location, Guide, Aim, Connection,
  Plus, Minus, Sort, MapLocation, Delete, 
  TrendCharts, Timer, Money, List
} from '@element-plus/icons-vue'

// ==================== 状态管理 ====================
const map = ref(null)
const AMap = ref(null)
const currentTool = ref('')
const mapType = ref('standard')
const showRoutePanel = ref(false)
const searchKeyword = ref('')
const measureResult = ref('')
const routeResult = ref(null)
const routeSteps = ref([])
const routeLoading = ref(false)
const selectingPoint = ref('') // 'start' 或 'end'

// 路线规划表单（保存地址用于显示，坐标用于路线规划）
const routeForm = reactive({
  start: '',
  end: '',
  mode: 'driving',
  startCoords: null, // 起点坐标 [lng, lat]
  endCoords: null    // 终点坐标 [lng, lat]
})

// 工具变量
let driving = null
let walking = null
let riding = null
let placeSearch = null
let geocoder = null

// 标记管理
const routeMarkers = ref([]) // 存储路线规划相关的标记
let startMarker = null // 起点标记
let endMarker = null // 终点标记
let currentLocationMarker = null
let ruler = null // 测距工具实例
let measureMarkers = [] // 测距标记点
let measurePolyline = null // 测距线
let searchMarkers = [] // 搜索标记点
let mapClickHandler = null // 地图点击处理器引用

// ==================== 初始化 ====================
onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
  }
})

// 初始化地图
const initMap = () => {
  if (typeof window.AMap === 'undefined') {
    ElMessage.error('地图API加载失败，请检查网络连接')
    return
  }

  AMap.value = window.AMap

  map.value = new AMap.value.Map('amap-container', {
    zoom: 12,
    center: [120.15, 30.25],
    viewMode: '3D',
    pitch: 0,
    rotation: 0,
    mapStyle: 'amap://styles/normal'
  })

  // 添加控件
  AMap.value.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
    map.value.addControl(new AMap.value.Scale())
    map.value.addControl(new AMap.value.ToolBar())
  })

  // 初始化工具
  initTools()

  ElMessage.success('地图加载成功')
}

// 初始化工具
const initTools = () => {
  AMap.value.plugin([
    'AMap.Driving',
    'AMap.Walking',
    'AMap.Riding',
    'AMap.PlaceSearch',
    'AMap.Geocoder'
  ], () => {
    // 路线规划工具 - 使用前端渲染模式
    driving = new AMap.value.Driving({
      map: map.value,
      panel: null,
      policy: AMap.value.DrivingPolicy.LEAST_TIME // 最快捷模式
    })

    walking = new AMap.value.Walking({
      map: map.value,
      panel: null
    })

    riding = new AMap.value.Riding({
      map: map.value,
      panel: null
    })

    // 地点搜索
    placeSearch = new AMap.value.PlaceSearch({
      map: map.value,
      pageSize: 10
    })

    // 地理编码
    geocoder = new AMap.value.Geocoder()
    
    console.log('地图工具初始化完成:', { driving, walking, riding, geocoder })
  })
}

// ==================== 搜索功能 ====================
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  if (!placeSearch) {
    ElMessage.warning('搜索功能正在初始化，请稍后再试')
    return
  }

  // 搜索前先清除之前的搜索标记
  clearSearchMarkers()

  placeSearch.search(searchKeyword.value, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois.length > 0) {
      const pois = result.poiList.pois
      
      // 定位到第一个结果
      const firstPoi = pois[0]
      map.value.setCenter([firstPoi.location.lng, firstPoi.location.lat])
      map.value.setZoom(15)
      
      // 为所有搜索结果添加标记
      pois.forEach((poi, index) => {
        const marker = new AMap.value.Marker({
          position: [poi.location.lng, poi.location.lat],
          title: poi.name,
          label: {
            content: poi.name,
            offset: new AMap.value.Pixel(0, -30),
            direction: 'top'
          }
        })
        
        // 先保存到数组，再添加到地图
        searchMarkers.push(marker)
        marker.setMap(map.value)
      })
      
      console.log('已创建搜索标记数量:', searchMarkers.length)
      
      ElMessage.success(`找到 ${pois.length} 个结果，点击输入框的清除按钮可清除标记`)
    } else {
      ElMessage.warning('未找到相关地点')
    }
  })
}

// 清除搜索标记
const clearSearchMarkers = () => {
  console.log('清除搜索标记，当前标记数量:', searchMarkers.length)
  if (searchMarkers.length > 0 && map.value) {
    searchMarkers.forEach(marker => {
      if (marker) {
        // 先移除标签
        marker.setLabel(null)
        // 再移除标记
        marker.setMap(null)
        map.value.remove(marker)
      }
    })
    searchMarkers = []
    console.log('搜索标记已清除')
    ElMessage.success('已清除搜索标记')
  }
}

// ==================== 测距功能 ====================
const activateTool = (tool) => {
  if (currentTool.value === tool) {
    // 如果再次点击，关闭工具
    deactivateMeasureTool()
    return
  }

  currentTool.value = tool

  if (tool === 'measure') {
    startMeasure()
  }
}

// 开始测距
const startMeasure = () => {
  // 清除之前的测量
  clearMeasure()
  
  // 重置测量点数组
  measureMarkers = []
  
  ElMessage.info('请在地图上点击两个点进行测距')
  
  // 添加地图点击事件
  map.value.on('click', handleMeasureClick)
}

// 处理测距点击
const handleMeasureClick = (e) => {
  const position = [e.lnglat.lng, e.lnglat.lat]
  
  // 添加标记
  const marker = new AMap.value.Marker({
    position: position,
    icon: new AMap.value.Icon({
      size: new AMap.value.Size(25, 34),
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
      imageSize: new AMap.value.Size(25, 34)
    }),
    map: map.value
  })
  
  measureMarkers.push(marker)
  
  // 如果已经有两个点，计算距离
  if (measureMarkers.length === 2) {
    const point1 = measureMarkers[0].getPosition()
    const point2 = measureMarkers[1].getPosition()
    
    // 绘制连线
    measurePolyline = new AMap.value.Polyline({
      path: [point1, point2],
      strokeColor: '#FF0000',
      strokeWeight: 3,
      strokeStyle: 'solid',
      map: map.value
    })
    
    // 计算距离
    const distance = Math.round(point1.distance(point2))
    measureResult.value = `测量距离：${distance}米 (${(distance / 1000).toFixed(2)}公里)`
    
    // 移除点击事件
    map.value.off('click', handleMeasureClick)
    
    ElMessage.success('测距完成')
    
    // 重置工具状态
    setTimeout(() => {
      currentTool.value = ''
    }, 100)
  } else {
    ElMessage.info('请点击第二个点')
  }
}

// 停用测距工具
const deactivateMeasureTool = () => {
  currentTool.value = ''
  map.value.off('click', handleMeasureClick)
  ElMessage.info('已取消测距')
}

// 清除测量
const clearMeasure = () => {
  // 清除标记
  if (measureMarkers.length > 0) {
    measureMarkers.forEach(marker => {
      map.value.remove(marker)
    })
    measureMarkers = []
  }
  
  // 清除线
  if (measurePolyline) {
    map.value.remove(measurePolyline)
    measurePolyline = null
  }
  
  // 移除点击事件
  map.value.off('click', handleMeasureClick)
  
  measureResult.value = ''
  currentTool.value = ''
  ElMessage.info('测量已清除')
}

// ==================== 路线规划 ====================
// 使用当前位置
const useCurrentLocation = () => {
  if (!geocoder) {
    ElMessage.warning('地图工具正在初始化，请稍后再试')
        return
      }
      
  ElMessage.info('正在获取当前位置...')
  
  AMap.value.plugin('AMap.Geolocation', () => {
    const geolocation = new AMap.value.Geolocation({
      enableHighAccuracy: true,
      timeout: 15000, // 增加超时时间到15秒
      buttonPosition: 'RB',
      convert: true, // 自动转换为高德坐标
      showButton: false,
      showMarker: false,
      showCircle: false,
      extensions: 'all' // 返回更多信息
    })
    
    geolocation.getCurrentPosition((status, result) => {
      console.log('定位结果:', status, result)
      
      if (status === 'complete') {
        const position = result.position
        const lng = position.lng
        const lat = position.lat
        console.log('定位坐标:', lng, lat)
        
        // 先保存坐标（确保可以使用）
        const coordString = `${lng},${lat}`
        
        // 先保存坐标
        routeForm.startCoords = [lng, lat]
        
        // 尝试反向地理编码获取地址
        geocoder.getAddress([lng, lat], (geoStatus, geoResult) => {
          console.log('地理编码结果:', geoStatus, geoResult)
          
          if (geoStatus === 'complete' && geoResult.regeocode) {
            // 尝试获取更详细的地址信息
            const regeocode = geoResult.regeocode
            let address = ''
            let comp = null
            
            // 优先使用详细地址组合
            if (regeocode.addressComponent) {
              comp = regeocode.addressComponent
              const parts = []
              if (comp.province) parts.push(comp.province)
              if (comp.city) parts.push(comp.city)
              if (comp.district) parts.push(comp.district)
              if (comp.township) parts.push(comp.township)
              if (comp.street) parts.push(comp.street)
              if (comp.streetNumber) parts.push(comp.streetNumber)
              
              address = parts.join('') || regeocode.formattedAddress
            } else {
              address = regeocode.formattedAddress
            }
            
            // 如果地址太简单，添加坐标信息
            if (address.length < 15 || !comp || (!comp.streetNumber && !comp.township)) {
              address = `${address} (${lng.toFixed(6)}, ${lat.toFixed(6)})`
            }
            
            // 显示地址
            routeForm.start = address
            ElMessage.success(`已获取当前位置: ${address}`)
          } else {
            // 地理编码失败，使用坐标显示
            routeForm.start = `坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`
            ElMessage.success('已获取当前位置坐标')
          }
          
          // 移动地图中心到当前位置
          map.value.setCenter([lng, lat])
          map.value.setZoom(15)
          
          // 清除之前的定位标记（避免和路线规划标记重叠）
          if (currentLocationMarker) {
            map.value.remove(currentLocationMarker)
            currentLocationMarker = null
          }
          
          // 清除旧的起点标记
          if (startMarker) {
            map.value.remove(startMarker)
            startMarker = null
          }
          
          // 添加路线规划的起点标记
          const startMarkerIcon = `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="48" height="60" viewBox="0 0 48 60"><defs><linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" style="stop-color:#4facfe;stop-opacity:1" /><stop offset="100%" style="stop-color:#00f2fe;stop-opacity:1" /></linearGradient><filter id="shadow" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity="0.4"/></filter></defs><circle cx="24" cy="24" r="20" fill="url(#grad1)" opacity="0.2"/><path d="M24 2 C15 2 8 9 8 18 C8 27 24 46 24 46 C24 46 40 27 40 18 C40 9 33 2 24 2 Z" fill="url(#grad1)" filter="url(#shadow)"/><circle cx="24" cy="18" r="8" fill="white"/><circle cx="24" cy="18" r="5" fill="#4facfe"/><text x="24" y="23" font-family="Arial" font-size="14" font-weight="bold" fill="white" text-anchor="middle">A</text></svg>`)}`
          
          startMarker = new AMap.value.Marker({
            position: [lng, lat],
            icon: new AMap.value.Icon({
              size: new AMap.value.Size(48, 60),
              image: startMarkerIcon,
              imageSize: new AMap.value.Size(48, 60),
              imageOffset: new AMap.value.Pixel(0, 0)
            }),
            offset: new AMap.value.Pixel(-24, -60),
            anchor: 'bottom-center',
            title: '起点',
            map: map.value
          })
          
          // 将起点标记添加到管理数组
          routeMarkers.value.push(startMarker)
        })
      } else {
        // 定位失败处理
        console.error('定位失败:', result)
        
        // 根据不同的错误类型提供友好提示
        let errorMsg = '定位失败'
        if (result && result.message) {
          const msg = result.message.toLowerCase()
          if (msg.includes('timeout')) {
            errorMsg = '定位超时，请检查网络连接或允许浏览器获取位置权限'
          } else if (msg.includes('permission') || msg.includes('denied')) {
            errorMsg = '定位权限被拒绝，请在浏览器设置中允许位置访问'
          } else if (msg.includes('unavailable')) {
            errorMsg = '定位服务不可用'
          }
        }
        
        ElMessage.warning(`${errorMsg}，正在尝试IP定位...`)
        
        // 使用IP定位作为备选方案
        useIPLocation()
      }
    })
  })
}

// IP定位备选方案
const useIPLocation = () => {
  AMap.value.plugin('AMap.CitySearch', () => {
    const citySearch = new AMap.value.CitySearch()
    citySearch.getLocalCity((status, result) => {
      if (status === 'complete' && result.city) {
        routeForm.start = result.city
        ElMessage.success(`已使用IP定位到: ${result.city}（精度较低）`)
        
        // 移动地图到城市中心
        if (result.rectangle) {
          map.value.setBounds(result.rectangle)
        }
      } else {
        // 最后的备选方案：使用默认城市
        routeForm.start = '杭州市'
        ElMessage.error('定位失败，已设置默认城市: 杭州市')
      }
    })
  })
}

// 从地图选点
const selectFromMap = (type) => {
  if (!geocoder) {
    ElMessage.warning('地图工具正在初始化，请稍后再试')
    return
  }
  
  // 如果已经有选点监听器在工作，先移除
  if (mapClickHandler) {
    map.value.off('click', mapClickHandler)
    mapClickHandler = null
    ElMessage.closeAll()
    console.log('已移除旧的地图选点监听器')
  }
  
  // 如果正在测距，先关闭测距
  if (currentTool.value === 'measure') {
    clearMeasure()
  }
  
  // 关闭路线规划抽屉，方便用户选点
  showRoutePanel.value = false
  
  // 保存当前选择的类型（使用闭包锁定type值）
  const currentType = type
  selectingPoint.value = type
  const pointName = type === 'start' ? '起点' : '终点'
  
  console.log(`开始选择${pointName}，类型: ${currentType}`)
  
  // 延迟显示提示，等待抽屉关闭动画完成
  setTimeout(() => {
    ElMessage.info({
      message: `请在地图上点击选择${pointName}`,
      duration: 0, // 不自动关闭
      showClose: true
    })
  }, 300)
  
  // 临时地图点击事件
  const clickHandler = (e) => {
    const lng = e.lnglat.lng
    const lat = e.lnglat.lat
    const position = [lng, lat]
    const coordString = `${lng},${lat}`
    
    console.log(`选择${pointName}坐标:`, lng, lat)
    
    // 关闭提示消息
    ElMessage.closeAll()
    
    // 先保存坐标（使用闭包中的currentType，确保类型正确）
    if (currentType === 'start') {
      routeForm.startCoords = [lng, lat]
    } else {
      routeForm.endCoords = [lng, lat]
    }
    
    // 反向地理编码
    geocoder.getAddress(position, (status, result) => {
      console.log(`${pointName}地理编码结果:`, status, result)
      
      if (status === 'complete' && result.regeocode) {
        // 尝试获取更详细的地址信息
        const regeocode = result.regeocode
        let address = ''
        let comp = null
        
        // 优先使用详细地址组合
        if (regeocode.addressComponent) {
          comp = regeocode.addressComponent
          const parts = []
          if (comp.province) parts.push(comp.province)
          if (comp.city) parts.push(comp.city)
          if (comp.district) parts.push(comp.district)
          if (comp.township) parts.push(comp.township)
          if (comp.street) parts.push(comp.street)
          if (comp.streetNumber) parts.push(comp.streetNumber)
          
          address = parts.join('') || regeocode.formattedAddress
        } else {
          address = regeocode.formattedAddress
        }
        
        // 如果地址太简单（如只有道路名），添加坐标信息
        if (address.length < 15 || !comp || (!comp.streetNumber && !comp.township)) {
          address = `${address} (${lng.toFixed(6)}, ${lat.toFixed(6)})`
        }
        
        if (currentType === 'start') {
          routeForm.start = address
        } else {
          routeForm.end = address
        }
        ElMessage.success(`已选择${pointName}: ${address}`)
      } else {
        // 地理编码失败，使用坐标显示
        const coordDisplay = `坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`
        if (currentType === 'start') {
          routeForm.start = coordDisplay
        } else {
          routeForm.end = coordDisplay
        }
        ElMessage.success(`已选择${pointName}坐标`)
      }
      
      // 清除旧的同类型标记（起点或终点）
      if (currentType === 'start' && startMarker) {
        map.value.remove(startMarker)
        startMarker = null
      } else if (currentType === 'end' && endMarker) {
        map.value.remove(endMarker)
        endMarker = null
      }
      
      // 添加标记显示选择的位置
      const markerIcon = currentType === 'start'
        ? `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="48" height="60" viewBox="0 0 48 60"><defs><linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" style="stop-color:#4facfe;stop-opacity:1" /><stop offset="100%" style="stop-color:#00f2fe;stop-opacity:1" /></linearGradient><filter id="shadow" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity="0.4"/></filter></defs><circle cx="24" cy="24" r="20" fill="url(#grad1)" opacity="0.2"/><path d="M24 2 C15 2 8 9 8 18 C8 27 24 46 24 46 C24 46 40 27 40 18 C40 9 33 2 24 2 Z" fill="url(#grad1)" filter="url(#shadow)"/><circle cx="24" cy="18" r="8" fill="white"/><circle cx="24" cy="18" r="5" fill="#4facfe"/><text x="24" y="23" font-family="Arial" font-size="14" font-weight="bold" fill="white" text-anchor="middle">A</text></svg>`)}`
        : `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="48" height="60" viewBox="0 0 48 60"><defs><linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" style="stop-color:#f093fb;stop-opacity:1" /><stop offset="100%" style="stop-color:#f5576c;stop-opacity:1" /></linearGradient><filter id="shadow" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity="0.4"/></filter></defs><circle cx="24" cy="24" r="20" fill="url(#grad2)" opacity="0.2"/><path d="M24 2 C15 2 8 9 8 18 C8 27 24 46 24 46 C24 46 40 27 40 18 C40 9 33 2 24 2 Z" fill="url(#grad2)" filter="url(#shadow)"/><circle cx="24" cy="18" r="8" fill="white"/><circle cx="24" cy="18" r="5" fill="#f5576c"/><text x="24" y="23" font-family="Arial" font-size="14" font-weight="bold" fill="white" text-anchor="middle">B</text></svg>`)}`
      
      const marker = new AMap.value.Marker({
        position: position,
        icon: new AMap.value.Icon({
          size: new AMap.value.Size(48, 60),
          image: markerIcon,
          imageSize: new AMap.value.Size(48, 60),
          imageOffset: new AMap.value.Pixel(0, 0)
        }),
        offset: new AMap.value.Pixel(-24, -60),
        anchor: 'bottom-center',
        title: pointName,
        map: map.value
      })
      
      // 保存标记引用
      if (currentType === 'start') {
        startMarker = marker
      } else {
        endMarker = marker
      }
      
      // 将标记添加到管理数组中（用于批量清除）
      routeMarkers.value.push(marker)
      
      // 选点完成后，重新打开路线规划抽屉
      setTimeout(() => {
        showRoutePanel.value = true
      }, 500)
    })
    
    // 移除事件监听，清理状态
    map.value.off('click', clickHandler)
    mapClickHandler = null
    selectingPoint.value = ''
    console.log(`${pointName}选择完成，已清理监听器`)
  }
  
  // 保存并添加地图点击监听
  mapClickHandler = clickHandler
  map.value.on('click', clickHandler)
  console.log(`已添加${pointName}选点监听器`)
}

// 交换起点和终点
const swapStartEnd = () => {
  if (!routeForm.start && !routeForm.end) {
    ElMessage.warning('请先输入起点和终点')
    return
  }
  
  // 交换地址
  const tempAddress = routeForm.start
  routeForm.start = routeForm.end
  routeForm.end = tempAddress
  
  // 交换坐标
  const tempCoords = routeForm.startCoords
  routeForm.startCoords = routeForm.endCoords
  routeForm.endCoords = tempCoords
  
  // 如果标记存在，交换标记的位置
  // 注意：标记图标不变（蓝色A始终是起点，红色B始终是终点），只是位置交换
  if (startMarker && endMarker) {
    const startPos = startMarker.getPosition()
    const endPos = endMarker.getPosition()
    
    startMarker.setPosition(endPos)
    endMarker.setPosition(startPos)
    
    console.log('已交换起点和终点标记位置')
  }
  
  console.log('已交换起点和终点')
  ElMessage.success('已交换起点和终点')
}

const planRoute = () => {
  if (!routeForm.start || !routeForm.end) {
    ElMessage.warning('请输入起点和终点')
    return
  }
  
  if (!geocoder || !driving || !walking || !riding) {
    ElMessage.warning('地图工具正在初始化，请稍后再试')
    return
  }
  
  console.log('开始路线规划:', {
    start: routeForm.start,
    end: routeForm.end,
    mode: routeForm.mode
  })

  // 清除之前的路线和标记
  if (driving) driving.clear()
  if (walking) walking.clear()
  if (riding) riding.clear()
  clearRouteMarkers()

  routeLoading.value = true

  // 地址解析（优先使用保存的坐标）
  const parseAddress = (address, savedCoords) => {
    return new Promise((resolve, reject) => {
      console.log('解析地址:', address, '保存的坐标:', savedCoords)
      
      // 优先使用保存的坐标
      if (savedCoords && Array.isArray(savedCoords) && savedCoords.length === 2) {
        console.log('✅ 使用保存的坐标:', savedCoords)
        resolve(savedCoords)
        return
      }
      
      // 如果是坐标格式
      if (/^[\d.]+,[\d.]+$/.test(address)) {
        const [lng, lat] = address.split(',')
        const coords = [parseFloat(lng), parseFloat(lat)]
        console.log('识别为坐标:', coords)
        resolve(coords)
      } 
      // 如果地址中包含坐标（格式：地址 (lng, lat)）
      else if (address.includes('(') && address.includes(')')) {
        const coordMatch = address.match(/\(([\d.]+),\s*([\d.]+)\)/)
        if (coordMatch) {
          const coords = [parseFloat(coordMatch[1]), parseFloat(coordMatch[2])]
          console.log('从地址中提取坐标:', coords)
          resolve(coords)
        } else {
          // 提取失败，尝试正常地址解析
          performGeocoding(address, resolve, reject)
        }
      } 
      else {
        // 地址解析
        performGeocoding(address, resolve, reject)
      }
    })
  }
  
  // 执行地理编码
  const performGeocoding = (address, resolve, reject) => {
    console.log('开始地理编码:', address)
    geocoder.getLocation(address, (status, result) => {
      console.log('地理编码结果:', status, result)
      
      if (status === 'complete' && result.geocodes && result.geocodes.length > 0) {
        const location = result.geocodes[0].location
        const coords = [location.lng, location.lat]
        console.log('地址解析成功:', coords)
        resolve(coords)
      } else {
        console.error('地址解析失败:', status, result)
        reject(new Error(`无法解析地址: ${address}`))
      }
    })
  }

  Promise.all([
    parseAddress(routeForm.start, routeForm.startCoords),
    parseAddress(routeForm.end, routeForm.endCoords)
  ]).then(([start, end]) => {
    console.log('地址解析完成，开始计算路线:', { start, end })
    
    // 检查起点和终点是否过于接近
    const startPoint = new AMap.value.LngLat(start[0], start[1])
    const endPoint = new AMap.value.LngLat(end[0], end[1])
    const directDistance = startPoint.distance(endPoint)
    
    console.log('起终点直线距离:', directDistance, '米')
    
    if (directDistance < 10) {
      routeLoading.value = false
      ElMessage.warning('起点和终点距离过近（小于10米），请选择距离更远的地点')
      return
    }
    
    calculateRoute(start, end)
  }).catch(error => {
    console.error('地址解析错误:', error)
    routeLoading.value = false
    ElMessage.error(error.message || '地址解析失败，请检查地址是否正确')
  })
}

const calculateRoute = (start, end) => {
  console.log('==================== 开始计算路线 ====================')
  console.log('起点坐标:', start)
  console.log('终点坐标:', end)
  
  const startPoint = new AMap.value.LngLat(start[0], start[1])
  const endPoint = new AMap.value.LngLat(end[0], end[1])
  
  console.log('创建LngLat对象:', { startPoint, endPoint })

  let routePlanner = driving
  let modeName = '驾车'
  if (routeForm.mode === 'walking') {
    routePlanner = walking
    modeName = '步行'
  } else if (routeForm.mode === 'riding') {
    routePlanner = riding
    modeName = '骑行'
  }
  
  console.log(`使用${modeName}规划器:`, routePlanner)
  
  if (!routePlanner) {
    console.error('❌ 路线规划器未初始化')
    routeLoading.value = false
    ElMessage.error('路线规划工具未就绪，请刷新页面重试')
        return
      }

  console.log('📍 调用 search 方法...')
  
  try {
    routePlanner.search(startPoint, endPoint, (status, result) => {
      console.log('==================== 路线规划回调 ====================')
      console.log('状态:', status)
      console.log('完整结果:', JSON.stringify(result, null, 2))
      
      routeLoading.value = false
      
      if (status === 'complete' && result.routes && result.routes.length > 0) {
        console.log('✅ 路线规划成功!')
        const route = result.routes[0]
        console.log('路线详情 (route):', route)
        console.log('完整结果 (result):', result)
        
        // 打印关键数据用于调试
        console.log('📏 距离 (route.distance):', route.distance, '米')
        console.log('⏱️ 时间 (route.time):', route.time, '秒')
        console.log('🚕 打车费用 (result.taxi_cost):', result.taxi_cost)
        console.log('📍 步骤数量:', route.steps ? route.steps.length : 0)
        
        // 提取距离和时间（兼容不同的数据结构）
        let totalDistance = 0
        let totalTime = 0
        
        // 方式1: 直接从 route 对象获取
        if (route.distance && route.distance > 0) {
          totalDistance = route.distance
          totalTime = route.time || 0
          console.log('✅ 使用 route.distance:', totalDistance)
        }
        // 方式2: 从 steps 累加计算
        else if (route.steps && route.steps.length > 0) {
          route.steps.forEach(step => {
            totalDistance += step.distance || 0
            totalTime += step.time || 0
          })
          console.log('✅ 从 steps 累加得到 distance:', totalDistance)
        }
        
        // 检查距离是否过小（可能是起点终点相同或太近）
        if (totalDistance < 10) {
          console.warn('⚠️ 距离过小，可能起点和终点太近或相同')
          ElMessage.warning('起点和终点距离过近，请选择距离较远的地点')
        }
        
        console.log('🎯 最终距离:', totalDistance, '米 =', (totalDistance / 1000).toFixed(2), '公里')
        console.log('🎯 最终时间:', totalTime, '秒 =', Math.floor(totalTime / 60), '分钟')
        
        // 基本信息
        routeResult.value = {
          distance: totalDistance > 0 ? `${(totalDistance / 1000).toFixed(2)} 公里` : '未知距离',
          duration: totalTime > 0 ? formatDuration(totalTime) : '未知时间',
          routeName: `${modeName}路线`
        }
        
        // 驾车模式显示打车费用
        if (routeForm.mode === 'driving' && result.taxi_cost) {
          routeResult.value.taxiFee = Math.round(result.taxi_cost)
        }
        
        // 提取路线步骤
        routeSteps.value = []
        if (route.steps && route.steps.length > 0) {
          console.log('📋 处理 steps，总数:', route.steps.length)
          route.steps.forEach((step, index) => {
            console.log(`  步骤 ${index + 1}:`, {
              instruction: step.instruction,
              distance: step.distance,
              time: step.time,
              road: step.road
            })
            
            routeSteps.value.push({
              instruction: step.instruction || step.road || `步骤 ${index + 1}`,
              distance: step.distance > 1000 
                ? `${(step.distance / 1000).toFixed(2)} 公里` 
                : `${Math.round(step.distance)} 米`,
              duration: step.time ? formatDuration(step.time) : ''
            })
          })
          console.log('✅ 处理完成，routeSteps:', routeSteps.value)
        }
        
        // 调整地图视野以显示完整路线
        map.value.setFitView()
        
        ElMessage.success('路线规划成功')
      } else if (status === 'error') {
        console.error('❌ 路线规划失败!')
        console.error('错误信息:', result)
        
        // 详细的错误信息
        let errorMsg = `${modeName}路线规划失败`
        
        if (typeof result === 'string') {
          if (result === 'INVALID_USER_SCODE') {
            errorMsg = 'Key权限不足，请重新申请Key并确保开通路径规划服务'
            console.error('解决方案:')
            console.error('1. 访问 https://console.amap.com/dev/key/app')
            console.error('2. 创建新Key，平台选择"Web端(JS API)"')
            console.error('3. 替换 index.html 中的 Key')
          } else if (result === 'INVALID_PARAMS') {
            errorMsg = '起点或终点参数错误，请检查地址'
          } else if (result === 'ENGINE_RESPONSE_DATA_ERROR') {
            errorMsg = '地址无法识别，请使用更具体的地址描述'
      } else {
            errorMsg = `${modeName}路线规划失败: ${result}`
          }
        }
        
        ElMessage.error(errorMsg)
      } else {
        console.warn('⚠️ 未知状态:', status)
        ElMessage.error(`${modeName}路线规划失败，请检查起点和终点是否正确`)
      }
    })
    
    console.log('search 方法已调用，等待回调...')
      } catch (error) {
    console.error('❌ 调用 search 异常:', error)
    routeLoading.value = false
    ElMessage.error(`路线规划出错: ${error.message}`)
  }
}

// 格式化时间
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
      } else {
    return `${minutes}分钟`
  }
}

// 清除路线标记
const clearRouteMarkers = () => {
  routeMarkers.value.forEach(marker => {
    if (marker && map.value) {
      map.value.remove(marker)
    }
  })
  routeMarkers.value = []
  
  // 重置起点和终点标记引用
  startMarker = null
  endMarker = null
}

// 清除路线
const clearRoute = () => {
  // 清除路线规划器绘制的路线
  if (driving) driving.clear()
  if (walking) walking.clear()
  if (riding) riding.clear()
  
  // 清除所有路线相关的标记
  clearRouteMarkers()
  
  // 清除路线结果
  routeResult.value = null
  routeSteps.value = []
  
  // 清除起点和终点的地址输入框
  routeForm.start = ''
  routeForm.end = ''
  
  // 清除保存的坐标
  routeForm.startCoords = null
  routeForm.endCoords = null
  
  ElMessage.info('路线已清除')
}

// 关闭路线规划面板
const handleRoutePanelClose = () => {
  // 关闭面板时不清除标记，让用户可以继续查看
  // 只有点击"清除路线"按钮时才会清除标记
  
  // 如果正在选点，取消选点状态并清理监听器
  if (selectingPoint.value) {
    selectingPoint.value = ''
    ElMessage.closeAll()
    
    // 清理地图点击监听器
    if (mapClickHandler) {
      map.value.off('click', mapClickHandler)
      mapClickHandler = null
      console.log('关闭面板时已清理地图选点监听器')
    }
  }
}

// ==================== 地图控制 ====================
const changeMapType = (type) => {
  if (!map.value) return
  
  if (type === 'satellite') {
    const satellite = new AMap.value.TileLayer.Satellite()
    map.value.add(satellite)
    map.value.setLayers([satellite])
  } else {
    const defaultLayer = new AMap.value.TileLayer()
    map.value.setLayers([defaultLayer])
  }
}

const locateUser = () => {
  AMap.value.plugin('AMap.Geolocation', () => {
    const geolocation = new AMap.value.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000
    })
    
    geolocation.getCurrentPosition((status, result) => {
      if (status === 'complete') {
        map.value.setCenter([result.position.lng, result.position.lat])
        map.value.setZoom(15)
        
        // 移除旧标记
        if (currentLocationMarker) {
          map.value.remove(currentLocationMarker)
        }
        
        // 创建定位标记（使用不同的样式以区分路线规划标记）
        const locationIcon = `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><defs><radialGradient id="locGrad" cx="50%" cy="50%"><stop offset="0%" style="stop-color:#409eff;stop-opacity:1" /><stop offset="100%" style="stop-color:#409eff;stop-opacity:0.3" /></radialGradient></defs><circle cx="20" cy="20" r="18" fill="url(#locGrad)" opacity="0.3"/><circle cx="20" cy="20" r="12" fill="#409eff" opacity="0.5"/><circle cx="20" cy="20" r="6" fill="#fff" stroke="#409eff" stroke-width="2"/><circle cx="20" cy="20" r="3" fill="#409eff"/></svg>`)}`
        
        currentLocationMarker = new AMap.value.Marker({
          position: [result.position.lng, result.position.lat],
          icon: new AMap.value.Icon({
            size: new AMap.value.Size(40, 40),
            image: locationIcon,
            imageSize: new AMap.value.Size(40, 40)
          }),
          offset: new AMap.value.Pixel(-20, -20),
          title: '当前位置',
          map: map.value
        })
        
        ElMessage.success('定位成功')
      } else {
        ElMessage.error('定位失败：' + result.message)
      }
    })
  })
}

const zoomIn = () => {
  if (map.value) {
    map.value.zoomIn()
  }
}

const zoomOut = () => {
  if (map.value) {
    map.value.zoomOut()
  }
}
</script>

<style scoped>
.map-module {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 工具栏 */
.map-toolbar {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 20px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.search-section {
  flex: 1;
  max-width: 500px;
}

.search-input {
  width: 100%;
}

.function-buttons {
  display: flex;
  gap: 10px;
}

.map-type-switch {
  margin-left: auto;
}

/* 地图主体 */
.map-main-container {
  flex: 1;
  display: flex;
  position: relative;
  overflow: hidden;
}

.map-container-wrapper {
  flex: 1;
  position: relative;
}

.amap-container {
  width: 100%;
  height: 100%;
}

/* 地图控制按钮 */
.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 10;
}

.map-controls .el-button {
  background: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

/* 测量结果 */
.measure-result {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  min-width: 300px;
}

/* 路线规划面板 */
.route-panel {
  padding: 20px;
}

.route-result {
  margin-top: 20px;
}

/* 路线规划面板样式 */
.route-panel {
  padding: 10px;
}

.location-actions {
  display: flex;
  gap: 10px;
  margin-top: 8px;
}

.swap-button-wrapper {
  display: flex;
  justify-content: center;
  margin: -10px 0;
  position: relative;
  z-index: 1;
}

.route-result {
  margin-top: 20px;
}

.route-info-card {
  margin-bottom: 20px;
}

.route-info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.info-value {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.info-value.highlight {
  color: #409EFF;
  font-size: 16px;
}

.route-steps {
  margin-top: 20px;
}

.step-content {
  padding: 5px 0;
}

.step-instruction {
  font-size: 14px;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.5;
}

.step-info {
  display: flex;
  gap: 8px;
}

/* 响应式 */
@media (max-width: 992px) {
  .map-toolbar {
    flex-wrap: wrap;
  }
  
  .search-section {
    width: 100%;
    max-width: none;
  }
  
  .function-buttons {
    flex-wrap: wrap;
  }
}

</style>
